//
//  JMLoginVC.m
//  NewiOSProject
//
//  Created by MAC on 2023/9/1.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMLoginVC.h"
#import "JMCaptcheButton.h"
#import <CoreLocation/CoreLocation.h>
#import "JMTenLocationManager.h"

@interface JMLoginVC ()<JMPublicAlertViewDelegate,UITextFieldDelegate,CLLocationManagerDelegate>
/**
 0 初始化 或者 清空状态（输入手机号）
 1.已发送验证码，已发送验证码，倒计时进行中（输入验证码）
 2.已发送验证码，已发送验证码，倒计时结束
 */
@property (nonatomic, assign)NSInteger state;
@property (nonatomic, strong)NSString *telNumber;//当前手机号
@property (nonatomic, strong)NSString *codeNumber;//当前验证码

@property (nonatomic, strong)UIButton *reinputBtn;//返回重新输入
@property (nonatomic, strong)UILabel *areaAndPhoneLab;//区号加手机号一体

@property (nonatomic, strong)UIView *textTContentV;
@property (nonatomic, strong)UIView *textTLine;//输入框底部线条
@property (nonatomic, strong)UIButton *areaNumLab;//输入框左侧，显示已选的区号
@property (nonatomic, strong)UITextField *phoneAndCodeTf;//手机号验证码输入框
@property (nonatomic, strong)UILabel *agreementLab;//隐私协议


@property (nonatomic, strong)JMCaptcheButton *fetchCodeBtn;//获取手机号
@property (nonatomic, strong)JMLoadingButton *voiceCodeBtn;//语音获取手机号
@property (nonatomic, strong)JMLoadingButton *loginBtn;//获取验证码/登陆按钮
@property (nonatomic, strong)JMPublicAlertView *voiceCodeAlertV;//语音验证码弹窗
@property (nonatomic, strong)JMPublicAlertView *agreementAlertV;//隐私协议弹窗

@property (nonatomic, strong)CLLocationManager *locationManager;
@end

@implementation JMLoginVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(posted:) name:UIMenuControllerDidHideMenuNotification object:nil];

    [self setUI];
    [self getAuth];
}

-(void)getAuth{
    [[JMTenLocationManager shareManager]ten_requestLocationRequest:^(BOOL granted, CLAuthorizationStatus status) {
        if (granted) {
            self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationManager.distanceFilter = 10.0f;
            [_locationManager requestWhenInUseAuthorization];
            [self.locationManager startUpdatingLocation];
        }
    }];
}

-(void)setUI{
    @weakify(self);
    UIImageView *topImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), ScaleW(300)))];
    topImgV.image = ImageNamed(@"login_topBg");
    [self.view addSubview:topImgV];
    
    
    UIImageView *logoImg = [[UIImageView alloc]initWithFrame:(CGRectMake(24, NAVIGATION_BAR_HEIGHT()+20, 64, 64))];
    [logoImg setImage:ImageNamed(@"login_logo")];
    [self.view addSubview:logoImg];
    
    
    UILabel *titleLab = [JMControl createLabelWithFrame:(CGRectMake(logoImg.left, logoImg.bottom+12, kAppW(), 80)) Font:fontWithWeight(24, UIFontWeightMedium) Text:@"Bienvenido a\nMóvil Loan" color:WhiteColor()];
    [self.view addSubview:titleLab];
    
    UILabel *loginTitleLab = [JMControl createLabelWithFrame:(CGRectMake(logoImg.left, topImgV.bottom+20, kAppW(), 35)) Font:fontWithWeight(24, UIFontWeightBold) Text:@"Iniciar sesión" color:Hex_Str_COLOR(@"#222222")];
    [self.view addSubview:loginTitleLab];

    //手机号显示区域
    _reinputBtn = [JMControl createButtonWithFrame:(CGRectMake(loginTitleLab.left, loginTitleLab.bottom+41, 24, 24)) ImageName:@"login_back" Target:self Action:@selector(clearPhoneNumber) font:nil Title:nil];
    [self.view addSubview:_reinputBtn];
    
    
    _areaAndPhoneLab = [[UILabel alloc]initWithFrame:(CGRectMake(loginTitleLab.left, 0, kAppW(), FontH(18)))];
    _areaAndPhoneLab.textColor = Text_COLOR_LEVEL2();
    _areaAndPhoneLab.font = fontWithWeight(17, UIFontWeightMedium);
    _areaAndPhoneLab.text = @"Número de teléfono";
    [self.view addSubview:_areaAndPhoneLab];
    _areaAndPhoneLab.centerY = _reinputBtn.centerY;
    
    
    
    //手机号验证码输入区域
    _textTContentV = [[UIView alloc]initWithFrame:(CGRectMake(loginTitleLab.left, _areaAndPhoneLab.bottom+12, self.view.width-36, 52))];
    [self.view addSubview:_textTContentV];
    
    //区号选额
    _areaNumLab = [JMControl createLabelWithFrame:(CGRectZero) Font:fontWithWeight(16, UIFontWeightMedium) Text:@"+52" color:Text_COLOR_LEVEL2()];
    [_textTContentV addSubview:_areaNumLab];
    
    [_areaNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        make.left.equalTo(self.textTContentV).offset(18);
        make.centerY.equalTo(self.textTContentV);
        make.width.lessThanOrEqualTo(@90);
    }];
    
    _textTLine = [[UIView alloc]initWithFrame:(CGRectMake(0, _textTContentV.height-1, _textTContentV.width, 1))];
    _textTLine.backgroundColor = Hex_Str_COLOR(@"#EBEBED");
    [_textTContentV addSubview:_textTLine];
    
    //获取验证码
    _fetchCodeBtn = [[JMCaptcheButton alloc]init];
    _fetchCodeBtn.interval = 60;
    _fetchCodeBtn.disabledTitleColor = Hex_Str_COLOR(@"#3C57F8");
    _fetchCodeBtn.titleLabel.font = fontWithWeight(14, UIFontWeightMedium);
    [_fetchCodeBtn setTitle:@"Conseguir código" forState:(UIControlStateNormal)];
    [_fetchCodeBtn addTarget:self action:@selector(fetchCodeCount:)
            forControlEvents:(UIControlEventTouchUpInside)];
    _fetchCodeBtn.tag = 11;

    [_fetchCodeBtn setTitleColor:Hex_Str_COLOR(@"#3C57F8") forState:(UIControlStateNormal)];
    [_textTContentV addSubview:_fetchCodeBtn];
    [self.fetchCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.right.equalTo(self.textTContentV.mas_right);
        make.top.bottom.equalTo(self.textTContentV);
        CGFloat w = CalculateLabelWidth(20, Font(14), @"Conseguir código")+20;
        make.width.equalTo(@(w));
    }];
    self.fetchCodeBtn.cornerRadius = 5;
    
    _fetchCodeBtn.countStartBlock = ^{
        @strongify(self)
        [self updateUI];
    };
    
    _fetchCodeBtn.countFinshBlock = ^{
        @strongify(self)
        [self updateUI];
        if (self.voiceCodeAlertV) {
            self.voiceCodeAlertV.secondBtn.enable = YES;
        }
        [self.fetchCodeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            @strongify(self);
            make.right.equalTo(self.textTContentV.mas_right).offset(-10);
            make.top.bottom.equalTo(self.textTContentV);
            CGFloat w = CalculateLabelWidth(20, Font(14), @"Conseguir código")+20;
            make.width.equalTo(@(w));
        }];
        if (self.phoneAndCodeTf.text.length) {
            self.loginBtn.enable = YES;
        }
    };
    _fetchCodeBtn.countTimingBlock = ^{
        @strongify(self)
        [self.fetchCodeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            @strongify(self);
            make.right.equalTo(self.textTContentV.mas_right).offset(-10);
            make.top.bottom.equalTo(self.textTContentV);
            make.width.equalTo(@(ScaleW(60)));
        }];
        [self updateUI];
    };
    
    //验证码输入框
    _phoneAndCodeTf = [[UITextField alloc]init];
    _phoneAndCodeTf.placeholder = @"Número de teléfono";
    _phoneAndCodeTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneAndCodeTf.keyboardType = UIKeyboardTypeNumberPad;
    _phoneAndCodeTf.font = Font(15);
    [_textTContentV addSubview:_phoneAndCodeTf];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:_phoneAndCodeTf];
    
    //获取语音验证码
    _voiceCodeBtn = [[JMLoadingButton alloc]initWithFrame:(CGRectZero) title:@"Obtener el código de verificación de voz>" font:Font(12) titleLabelColor:Hex_Str_COLOR(@"#3C57F8") backgoundColor:UIColor.clearColor action:@selector(sendVoiceCode:) target:self];
    _voiceCodeBtn.tag = 10;
    [self.view addSubview:_voiceCodeBtn];
    [_voiceCodeBtn setImage:ImageNamed(@"login_voice") forState:(UIControlStateNormal)];
    [_voiceCodeBtn TiaoZhengButtonWithOffsit:4 TextImageSite:(UIButtonTextRight)];
    
    
    [_voiceCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.left.mas_equalTo(self.textTContentV.left);
        make.top.mas_equalTo(self.textTContentV.bottom+20);
        make.height.mas_equalTo(@40);
    }];
    _voiceCodeBtn.cornerRadius = 3;

 
    
    
    
    //协议
    _agreementLab = [[UILabel alloc]initWithFrame:(CGRectMake(_textTContentV.left,kAppH()- JF_BOTTOM_SPACE()-20-50, self.view.width-_textTContentV.left*2, 50))];
    _agreementLab.numberOfLines = 0;
    _agreementLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_agreementLab];
    
    NSString *agreementStr =@"Al iniciar sesión, significa que acepta la <Política de privacidad> y el<Acuerdo de usuario>";
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:ScaleW(12)], NSForegroundColorAttributeName: Hex_Str_COLOR(@"#9B9B9B")};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:agreementStr attributes:attributes];
    
    NSRange range = [agreementStr rangeOfString:@"<Política de privacidad>"];
    
    [text yy_setTextHighlightRange:range color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Política de privacidad"];

    }];
    NSRange range1 = [agreementStr rangeOfString:@"<Acuerdo de usuario>"];
    [text yy_setTextHighlightRange:range1 color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(LoginRegistrationAgreement) andTitle:@"Acuerdo de usuario"];
    }];
    _agreementLab.attributedText = text;
    
    //登陆和获取验证码按钮
    _loginBtn = [[JMLoadingButton alloc]initWithFrame:(CGRectMake(_textTContentV.left, _agreementLab.top-77, self.view.width-_textTContentV.left*2, 56)) title:@"Obtener codigo" font:Font(16) titleLabelColor:Button_ENABLE_TEXTCOLOR() backgoundColor:Button_ENABLE_BG_COLOR() action:@selector(loginBtnClick) target:self];
    _loginBtn.enable = NO;
    _loginBtn.cornerRadius = 28;
    [self.view addSubview:_loginBtn];
    
    [self updateUI];
    [self startTime];
}

-(void)updateUI{
    @weakify(self)
    
    [self.loginBtn setTitle:@"Siguiente" forState:(UIControlStateNormal)];
    self.reinputBtn.hidden = self.state==0;
    self.fetchCodeBtn.hidden = self.state==0;
    self.areaAndPhoneLab.left = self.state==0?24:self.reinputBtn.right;
    self.areaAndPhoneLab.text = self.state==0?@"Número de teléfono":[NSString stringWithFormat:@"+52 %@",self.telNumber];
    
    self.areaNumLab.hidden = self.state!=0;
    self.phoneAndCodeTf.placeholder = self.state==0?@"Número de teléfono":@"Código de verificación";
    self.voiceCodeBtn.hidden = self.state==0;
    
    [_phoneAndCodeTf mas_remakeConstraints:^(MASConstraintMaker *make) {
        @strongify(self)
        if (self.state==0) {
            make.left.equalTo(self.areaNumLab.mas_right);
            make.right.equalTo(self.textTContentV.mas_right);
            make.top.bottom.equalTo(self.textTContentV);
        }else{
            make.left.equalTo(@0);
            make.right.equalTo(self.fetchCodeBtn.mas_left);
            make.top.bottom.equalTo(self.textTContentV);
        }
    }];
}
//MARK: - Action

-(void)clearPhoneNumber{
    [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Phone_Auto_Cancel" Action:(BUTTON_CLICK)];

    self.phoneAndCodeTf.text = @"";
    self.telNumber = @"";
    self.codeNumber = @"";
    self.state = 0;
    [self.fetchCodeBtn stopTimer];
    [self updateUI];
}

-(void)loginBtnClick{
    
    if(self.state==0){//第一次获取验证码
        [self.view endEditing:YES];
        [self.agreementAlertV show];
        _agreementAlertV.closeBtn.frame = CGRectMake(kAppW()-48, 24, 24, 24);
        [_agreementAlertV.closeBtn setImage:ImageNamed(@"login_close") forState:(UIControlStateNormal)];
        [_agreementAlertV addSubview:_agreementAlertV.closeBtn];
    }
    
    if(self.state>0){//登录
        //获取验证码按钮
        NSDictionary *param;
        param =  @{@"loginName":self.telNumber,@"loginType":@"SMS",@"vcode":_phoneAndCodeTf.text?:@""};
        [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendLoginSms) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {

            self.phoneAndCodeTf.text = @"";
            [self.loginBtn endLoading];
            [self updateUI];
            [self stopAnimating];
            JMLoginUserModel *user = [JMProjectManager sharedJMProjectManager].loginUser;
            NSString *userId = [dataDic safeStringForKey:@"userId"];
            user.userId = userId;
            user.token = [dataDic safeStringForKey:@"token"];
            user.phone = self.telNumber;;
            [user save];
            
            [JMCommonMethod loginSuccessWithDict:dataDic];
            
            
            if([dataDic safeBoolForKey:@"register"]){//是注册
                //打点
                [JMCommonMethod uploadStatistics:@"Register" actionType:@"Register_Save" parameters:nil];

                //埋点
                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Register_Login" Action:(BUTTON_CLICK)];
                
                //追踪
                ADJEvent *event = [ADJEvent eventWithEventToken:@"qcme5u"];
                [event addCallbackParameter:@"eventKey" value:@"Register_Event"];
                [event addCallbackParameter:@"phone" value:user.phone?user.phone:@""];
                [event addCallbackParameter:@"userId" value:user.userId?user.userId:@""];
                [Adjust trackEvent:event];
                
            }else{//是登录
                [JMCommonMethod uploadStatistics:@"Register" actionType:@"Login_Save" parameters:nil];
                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Register_Login" Action:(BUTTON_CLICK)];

            }

        } fail:^(NSString * _Nonnull errorMsg) {
            [self stopAnimating];
            [self.loginBtn endLoading];
            [self showMessage:errorMsg];
            [self updateUI];
        }];
    }
}
- (void)posted:(NSNotification*)s{

}

//这里可以通过发送object消息获取注册时指定的UITextField对象
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];

    if(self.state==0){
        self.telNumber = sender.text;
        if(self.telNumber.length){
            self.loginBtn.enable = YES;
            
//            if (pasteboardString && [pasteboardString isEqualToString:sender.text]) {
//                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Phone_Input" Action:(PARSE)];
//
//            } else {
//                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Phone_Input"  Action:(INPUT)];
//
//            }
            [JMCommonMethod uploadStatistics:@"Register" actionType:@"Phone_Input" parameters:nil];
        }else{
            self.loginBtn.enable = NO;
        }
    }else{
        self.codeNumber = sender.text;
        if(self.codeNumber.length){
            self.loginBtn.enable = YES;

//            if (pasteboardString && [pasteboardString isEqualToString:sender.text]) {
//                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"VCode_Input"  Action:(PARSE)];
//
//            } else {
//                [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"VCode_Input"  Action:(INPUT)];
//            }
            [JMCommonMethod uploadStatistics:@"Register" actionType:@"VCode_Input" parameters:nil];
        }else{
            self.loginBtn.enable = NO;
        }
    }
    [self updateUI];
   
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if(self.state){
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Phone_Input"  Action:(GET_FOCUS)];

        [JMCommonMethod uploadStatistics:@"Register" actionType:@"Phone_Focus" parameters:nil];
    }else{
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"VCode_Input"  Action:(GET_FOCUS)];

        [JMCommonMethod uploadStatistics:@"Register" actionType:@"VCode_Focus" parameters:nil];
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if(self.state){
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Phone_Input"  Action:(LOST_FOCUS)];
    }else{
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"VCode_Input"  Action:(LOST_FOCUS)];
    }
}
-(void)fetchCodeCount:(UIButton *)sender{
    if (sender.tag==11) {
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"SMS_Send" Action:(BUTTON_CLICK)];
    }else{
        [JMCommonMethod userBehaviorTrack:@"VCodeDialog" FeatureName:@"SMS_Send" Action:(BUTTON_CLICK)];
    }
    [self.view endEditing:YES];
    NSDictionary *param = @{@"phone":self.telNumber,@"type":@"login",@"voiceCode":@"false"};
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendSmsCount) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [self.agreementAlertV dismiss];
        NSNumber *num = dataDic;
        if (num.intValue>3) {
            [self.voiceCodeAlertV show];
        }else{
            [self sendSMSCode];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self.agreementAlertV dismiss];
    }];
}
-(void)sendSMSCode{
    NSString *isVoice = @"false";;
    NSString *startActionType = @"SMS_Send_Click";
    NSString *successActionType = @"SMS_Send_Success";
    NSString *message = @"Código de verificación por SMS obtenido con éxito";
    [JMCommonMethod uploadStatistics:@"Register" actionType:startActionType parameters:@{@"phone":self.telNumber}];

    [self.fetchCodeBtn startLoading];
    NSDictionary *param = @{@"phone":self.telNumber,@"type":@"login",@"voiceCode":isVoice};
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendSms) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [self.fetchCodeBtn stopLoading];
        [self.agreementAlertV.firstBtn endLoading];
        
        [JMCommonMethod uploadStatistics:@"Register" actionType:successActionType parameters:@{@"phone":self.telNumber}];
        delayOperation(0, ^{
            
            [self showMessage:message];
            [self smsCodeSendSuccess];
        });
    } fail:^(NSString * _Nonnull errorMsg) {
        [self.fetchCodeBtn stopLoading];
        [self.voiceCodeAlertV.secondBtn endLoading];
        [self.loginBtn endLoading];
    }];
}
-(void)sendVoiceCode:(UIButton *)sender{//tag=0语音。1短信
    NSString *isVoice = @"true";;
    NSString *startActionType = @"Voice_Send_Click";
    NSString *successActionType = @"Voice_Send_Success";
    NSString *message = @"Le llamaremos en 5 min para darle el código de verificación.";
    [JMCommonMethod uploadStatistics:@"Register" actionType:startActionType parameters:@{@"phone":self.telNumber}];
    if (sender.tag==10) {
        [JMCommonMethod userBehaviorTrack:@"Register" FeatureName:@"Voice_Send" Action:(BUTTON_CLICK)];

    }else{
        [JMCommonMethod userBehaviorTrack:@"VCodeDialog" FeatureName:@"Voice_Send" Action:(BUTTON_CLICK)];
    }
    NSDictionary *param = @{@"phone":self.telNumber,@"type":@"login",@"voiceCode":isVoice};
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendSms) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [JMCommonMethod uploadStatistics:@"Register" actionType:successActionType parameters:@{@"phone":self.telNumber}];
            [self showMessage:message];
            [self voiceCodeSendSuccess];
    } fail:^(NSString * _Nonnull errorMsg) {
        [self.voiceCodeAlertV dismiss];
    }];
}
//MARK: -JMPublicAlertViewDelegate
- (void)didClickBtnAtIndex:(NSInteger)index withButton:(JMLoadingButton *)sender{
    if(sender.superview.tag==10){//协议
        [self fetchCodeCount:sender];
    }else{//语音
        if (sender.tag==1) {
            [self.loginBtn startLoading];
            [self sendSMSCode];
        }else{
            [self sendVoiceCode:sender];
        }
    }
}

-(void)voiceCodeSendSuccess{
    [self codeSendSuccess];
}
-(void)codeSendSuccess{
    [self.voiceCodeAlertV dismiss];
    self.state = 1;
    self.phoneAndCodeTf.text = @"";
    [self updateUI];
    self.loginBtn.enable = NO;
}
-(void)smsCodeSendSuccess{
    self.state=1;
    [self codeSendSuccess];
    [self.loginBtn endLoading];
    [self.fetchCodeBtn fire];
}
//MARK: -lazyLoad

-(JMPublicAlertView *)voiceCodeAlertV{
    if(!_voiceCodeAlertV){
        _voiceCodeAlertV = [[JMPublicAlertView alloc]
                            initWithFrame:(CGRectMake(0, 0, kAppW()-36, 294))
                            andTitle:@"Nota"
                            subTitle: @"Puede intentar obtener el código de verificación nuevamente o el código de verificación de voz"
                            BottomBtns:@[@"Obtener el código de verificación de voz",@"Obtener el código de verificación por SMS"]
                            Position:JMPublicAlertViewPositionCenter
                            btnDirection:JMPublicAlertViewButtonDirectionVer];
        _voiceCodeAlertV.delegate = self;
    }
    return _voiceCodeAlertV;
}
-(JMPublicAlertView *)agreementAlertV{
    if(!_agreementAlertV){
    
        _agreementAlertV = [[JMPublicAlertView alloc]
                            initWithFrame:(CGRectMake(0, 0, kAppW(), ScaleW(248)))
                            andTitle:@"Política de privacidad"
                            subTitle:nil
                            BottomBtns:@[@"Continuar"]
                            Position:JMPublicAlertViewPositionBottom
                            btnDirection:JMPublicAlertViewButtonDirectionVer];
        
        _agreementAlertV.tag = 10;
        _agreementAlertV.delegate = self;
        NSString *agreementStr =@"Al iniciar sesión, significa que acepta la <Política de privacidad> y el<Acuerdo de usuario>";
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:ScaleW(12)], NSForegroundColorAttributeName: Hex_Str_COLOR(@"#9B9B9B")};
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:agreementStr attributes:attributes];
        
        NSRange range = [agreementStr rangeOfString:@"<Política de privacidad>"];
        
        [text yy_setTextHighlightRange:range color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Política de privacidad"];

        }];
        NSRange range1 = [agreementStr rangeOfString:@"<Acuerdo de usuario>"];
        [text yy_setTextHighlightRange:range1 color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(LoginRegistrationAgreement) andTitle:@"Acuerdo de usuario"];
        }];
        _agreementAlertV.titleLab.top = 60;
        
        _agreementAlertV.subtitleLab.attributedText = text;
        
        CGSize introSize = CGSizeMake(_agreementAlertV.width-40, MAXFLOAT);
        YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:introSize text:text];
        CGFloat introHeight = layout.textBoundingSize.height;
        _agreementAlertV.subtitleLab.height = introHeight;
        _agreementAlertV.subtitleLab.top = _agreementAlertV.titleLab.bottom+12;
        
    }
    return _agreementAlertV;
}

#pragma mark - CLLocationManagerDelegate
//更新用户位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *currLocation = [locations lastObject];
    NSLog(@"当前经度=%f 当前纬度=%f 当前高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);

    @weakify(self)
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        @strongify(self);
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            JMLoginUserModel *user =  JMProjectManager.sharedJMProjectManager.loginUser;
            user.street = placeMark.name.length?placeMark.name:@"";
            user.city = placeMark.locality?placeMark.locality:@"";
            user.province = placeMark.administrativeArea?placeMark.administrativeArea:@"";
            user.latitude = @(currLocation.coordinate.latitude).stringValue;
            user.longitude = @(currLocation.coordinate.longitude).stringValue;
            [user save];
            [self.locationManager stopUpdatingLocation];
            
        } else if (error == nil && placemarks.count == 0) {
        } else if (error) {
        }
    }];
}
//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
   
}
-(void)dealloc{
    [_fetchCodeBtn stopTimer];
}
@end
